#include "sellermodel.h"
#include "../common/seller.h"

#include <QFile>
#include <QMessageBox>

SellerModel::SellerModel(QObject *parent) :
    QStandardItemModel(parent)
{

}

void SellerModel::clearSellersTurnOver()
{
    for (int row=0;row<rowCount ();row++)
    {
        cs8Seller* seller=item(row,0)->data(Qt::UserRole).value<cs8Seller*>();
        if (seller)
        {
            //seller->setTotalSum (0);
            seller->clearSales ();
            //double sum=seller->totalSum ();
        }
    }
}


bool SellerModel::readSellerList(const QString & fileName)
{
    QFile file(fileName);
    if (!file.open (QFile::ReadOnly))
    {
        return false;
    }

    QString data=file.readAll ();
    file.close ();

    clear ();

    QStringList rows=data.split ("\n");
    m_salesPeriods=rows.at(1).split (";");
    m_salesPeriods.removeFirst ();
    m_salesPeriods.removeFirst ();
    m_salesPeriods.removeFirst ();
    m_salesPeriods.removeFirst ();
    m_salesPeriods.removeFirst ();
    m_salesPeriods.removeDuplicates ();
    while (m_salesPeriods.last ().length ()<4)
        m_salesPeriods.removeLast ();

    setColumnCount (2 + m_salesPeriods.count ());
    setHorizontalHeaderLabels (QStringList() << trUtf8 ("Nummer") << trUtf8 ("Name") << m_salesPeriods);


    foreach (QString rowData,rows)
    {
        //qDebug() << "Reading row " << rowData;
        QStringList columns=rowData.split (";");
        for (int i=0;i<columns.count ();i++)
        {
            // check for ; enclosed in quotes
            if (columns.at(i).startsWith("\""))
            {
                columns[i]+=";"+columns.at (i+1);
                columns.removeAt (i+1);
            }
            columns[i].remove ("\"");
        }
        if (columns.count ()>3)
        {
            bool ok;
            // 1st column is a number ==> a valid seller row
            if (columns.at(0).toInt (&ok) && !columns.at(1).isEmpty ())
            {
                int row=rowCount ();

                insertRow(row);
                setData (index(row,0),columns.at(0).toInt ());
                setData (index (row,0),Qt::AlignCenter,Qt::TextAlignmentRole);

                setData(index(row,1),columns.at(1));
                for (int i=0;i<m_salesPeriods.count ();i++)
                {
                    setData (index (row,i+2),columns.at(i+5));
                    setData (index (row,i+2),Qt::AlignCenter,Qt::TextAlignmentRole);
                }
                cs8Seller *s=new cs8Seller(this);

                s->setName (columns.at(1));
                setData (index (row,0),QVariant::fromValue(s),Qt::UserRole);
            }
        }

    }
    return true;
}

QStringList SellerModel::salesPeriods() const
{
    return m_salesPeriods;
}
